<?php
namespace Home\Model;
use Think\Model;
class WechatModel extends Model {

	
	private $appid = 'wx1ee2660aebdf514f';
	private $appidSecret = 'd4624c36b6795d1d99dcf0547af5443d';


	public function getAppid() {
		return $this->appid;
	}

	public function getAppidSecret() {
		return $this->appidSecret;
	}




	//获取access_token
	public function getAccessToken() {
		$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appid&secret=$this->appidSecret";
		$res = $this->curl($url);
		$res = json_decode($res, true);
		return $res['access_token'];

	}



	/**
	*curl采集
	*@$url 采集的地址
	*@data 传递一个作为POST的字符串
	*/

	public function curl($url, $data = null) {

	    $curl = curl_init();
	    curl_setopt($curl, CURLOPT_URL, $url);
	    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
	    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

	    if (!empty($data)){
	        curl_setopt($curl, CURLOPT_POST, 1);
	        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
	    }

	    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	    $output = curl_exec($curl);
	    curl_close($curl);
	    return $output;
	}



	//对接成功时，打印的字符串
	public function valid() {
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()) {
        	echo $echoStr;
        	exit;
        }
    }


	//验证服务器和微信的服务器是否对接成功
	private function checkSignature() {

        if (!empty($this->token)) {
        	throw new Exception('请先设置你的token');
        }

        $signature = $_GET["signature"];		
        $timestamp = $_GET["timestamp"];		
        $nonce = $_GET["nonce"];				

		$tmpArr = array($this->token, $timestamp, $nonce);

		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		if( $tmpStr == $signature ) {
			return true;
		} else {
			return false;
		}

	}



	/**
	*创建菜单
	*@$json 传入一个json(具体格式请看微信文档)
	*@返回json(里面有微信api的调用结果)
	*/

	public function createMenu($json) {
	  $token = $this->getAccessToken();
      $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=$token";
      $result = $this->curl($url, $json);
      return $result;
	}


	//获取模板的id号
	public function templateId() {
		$token = $this->getAccessToken();
		$json =  '{"template_id_short":"TM00015"}';
		$url = "https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=$token";
		$templateId = $this->curl($url, $json);
		return $templateId;
	}

	/**
	*推送模板消息
	*@param传入json数据
	*/
	public function templateMsg($template) {
		$json = ($template);
		
		$token = "g0zhAVt89CdvaguDnzfjxj6Rcrd3wfGwt2Uh2FHQeELU7A9Sg4HsKf4E6ruLUK04AVb6W9HDlhazIHoBA0ozdT3luHliD0FRTgcZNpODZrQHMRdADACHM";

		//$token = '1zh7wT-SLCVqkst5lheRkzI5krZdnxlOVqWrQ9iLmUqUT5gcqX3oHhuCg7vFy_Ln3xbvOJvJie0OxKnAFBdU47afuKftLPSs5nW3C3FyA5uxLNLDjOiEx24DSoz0XakLCGOhABAMQY';
		$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$token";
		
		$res = $this->curl($url, $json);
	}

	/**
	*
	*OAuth2.0的弹出界面，和下面的getWxUserInfo一起来用
	*@param $redirectUrl 点击确认之后回调地址
	*@param $openIdOnly：true表示:只是获取openid   false表示:获取用户的openid face sex 
	*/
    public function OAuthUrl($redirectUrl, $openIdOnly) {

        $newUrl =  urlencode('http://'.$_SERVER['SERVER_NAME'].$redirectUrl);
        $scope = $openIdOnly ? 'snsapi_userinfo' : 'snsapi_base';

		$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->appid}&redirect_uri=$newUrl&response_type=code&scope=$scope&state=STATE#wechat_redirect";
        return $url;
    }


    /**
    *获取微信用户的信息
    */

    public function getWxUserInfo() {

    	$code = $_GET["code"];

        //获取用户的openid和access_token(这里的access_token和获取接口凭据的access_token不一样)
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appid}&secret={$this->appidSecret}&code=$code&grant_type=authorization_code";  
        $res = $this->curl($url);
        $userInfo = json_decode($res,true); 

        //用户的openid和access_token去换取用户的详细信息
        $accessToken = $userInfo['access_token']; 
        $openid = $userInfo['openid']; 
        $getInfoUrl = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$accessToken.'&openid='.$openid.'&lang=zh_CN'; 
        $res = $this->curl($getInfoUrl);
        $detailInfo = json_decode($res,true);
        return $detailInfo;
    }


    //通过openid获取用户信息
    public function info($openid) {

        $token = $this->getAccessToken();

        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$token&openid=$openid&lang=zh_CN";
        $res = $this->curl($url);
        return $res;


    }

}